<?php

namespace Flow;

use Helpers\Hrm;
use Flow\models\XhflowProcess;
use Flow\models\XhflowNode;

class FlowChoice extends Config {

    public $showSelect  = false;
    public $flowList    = [];
    public $nodeList    = [];

    function __construct($tag)
    {
        if (!$tag) {
            throw new \Exception('流程标识不可为空！');
        }
        $this->getProcess($tag);
        $this->getNode();
    }

    private function getProcess($tag)
    {
        $process = XhflowProcess::find([
            'columns'    => 'iProId AS id,sName AS name',
            'conditions' => 'bDelete = 0 AND sTag = :tag:',
            'bind'       => ['tag' => $tag]
        ]);
        if (!$process) {
            throw new \Exception('该标识下无流程模板！');
        }
        $this->flowList     = array_column($process->toArray(), 'name', 'id');
        $this->showSelect   = count($this->flowList) > 1;
    }

    private function getNode()
    {
        $flowIds = array_keys($this->flowList);
        $nodes   = XhflowNode::find([
            'columns'    => [
                'iNodeId AS nodeId',
                'iProId AS proId',
                'sName AS nodeName',
                'sTargetUser AS targetUser',
                'sTargetArea AS targetArea'
            ],
            'conditions' => 'bDelete = 0 AND iProId IN ({proId:array})',
            'bind'       => ['proId' => $flowIds],
            'order'      => 'iCode'
        ]);
        if (!$nodes) {
            throw new \Exception('该标识下节点！');
        }
        $nodes = $nodes->toArray();
        if (!$this->showSelect) {
            $this->nodeList[$flowIds[0]] = $nodes;
        }
        else {
            foreach ($nodes as $node) {
                $this->nodeList[$node['proId']][] = $node;
            }
        }
    }

    public function getFlowHtml()
    {
        //组合下拉框
        $selectHtml = $selectAttr = '';
        foreach ($this->flowList as $flowId => $flowName) {
            $selectHtml .= "<option value='{$flowId}'>{$flowName}</option>";
        }
        if (!$this->showSelect) {
            $selectAttr .= 'style="display:none;"';
        }
        $selectHtml = "<select class='form-control' name='_xh_flow_proId' {$selectAttr}>{$selectHtml}</select>";

        //组合流程内容
        $processHtml = [];
        foreach ($this->nodeList as $proId => $nodes) {
            $html = '';
            foreach ($nodes as $node) {
                $inputValue = '';                   //默认值
                $btnText    = 0;                    //按钮数字
                $btnClass   = ['btn', 'btn-sm'];    //按钮样式
                $btnAttr    = [];
                //有目标用户则赋值，显示人数，显示为success
                if ($node['targetUser']) {
                    $inputValue = trim($node['targetUser'], ',');
                    $btnText    = substr_count($node['targetUser'], ',') - 1;
                    $btnClass[] = 'btn-success';
                }
                else {
                    $btnClass[] = 'btn-danger';
                    if (strpos($node['targetArea'], 'dep') === 0) {
                        $area = explode(':', $node['targetArea']);
                        $btnAttr[] = 'data-target="dep"';
                        $btnAttr[] = "data-target-id='{$area[1]}'";
                    }
//                    elseif (strpos($node['targetArea'], 'all') === 0) {
//                        $btnAttr[] = 'data-target="all"';
//                    }
                }
                $btnClass = implode(' ', $btnClass);
                $btnAttr  = implode(' ', $btnAttr);
                $html .= "<div class='xh-flow-node xh-flow-node-waiting'><div><font>{$node['nodeName']}</font> <a class='{$btnClass}' {$btnAttr}>{$btnText}</a><input name='_xh_flow_node[{$node['nodeId']}]' value='{$inputValue}' /></div></div>";
            }
            $processHtml[$proId] = $html;
        }

        //处理js数据
        $jsVar = [
            'users'     => json_encode(Hrm::getFlowDepStaff(), JSON_UNESCAPED_UNICODE),
            'process'   => json_encode($processHtml, JSON_UNESCAPED_UNICODE)
        ];
        $jsString = '';
        foreach ($jsVar as $key => $value) {
            $jsString .= "var _xh_flow_{$key} = {$value};";
        }
        $jsString = "<script type='application/javascript'>{$jsString}</script>";
        return "<div class='xh-flow-area'>{$selectHtml}<div class='xh-flow-process'></div></div>{$jsString}";
    }


}